package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.common.enums.IEarlyWarningEnums;
import io.itit.ecp.admin.provide.action.req.EarlyWarningQueryReq;
import io.itit.ecp.admin.provide.action.req.EarlyWarningReq;
import io.itit.ecp.admin.provide.action.resp.EarlyWarningResp;
import io.itit.ecp.admin.provide.action.resp.EarlyWarningThresholdResp;
import io.itit.ecp.admin.provide.action.resp.EarlyWarningUserResp;
import io.itit.ecp.admin.provide.filter.IEarlyWarningFilter;
import io.itit.ecp.admin.provide.helper.SceneHelper;
import io.itit.ecp.admin.provide.renderer.EarlyWarningRenderer;
import io.itit.ecp.admin.server.entity.*;
import io.itit.ecp.admin.server.service.IEarlyWarningService;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.*;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.parse.ExcelParseManage;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：碳排放预警控制类
 * @Date：Create by 2023-12-04 15:28:53
 */
@Api(tags = "碳排放预警设置")
@RestController
@RequestMapping("/ecp-admin/carbonEmissionWarning")
public class CarbonEmissionWarningController {

    @Resource
    private IEarlyWarningService earlyWarningService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:warningSetting:search")
    public ResultResp<IPage<EarlyWarningResp>> queryPage(@RequestBody @Validated(IQueryPage.class) EarlyWarningQueryReq req) {
        Page<EarlyWarningResp> page = buildQW(req).joinPage(PageUtils.getPage(req, EarlyWarningResp.class), EarlyWarningResp.class);
        page.getRecords().forEach(warning -> {
            List<EarlyWarningThresholdResp> thresholdResps = earlyWarningService.getEarlyWarningThreshold(warning.getId())
                    .stream().map(item -> ConvertUtils.copy(item, EarlyWarningThresholdResp.class))
                    .collect(Collectors.toList());
            warning.setWarningThresholds(thresholdResps);
        });
        return ResultResp.success(SceneHelper.i().setSceneInfo(page));
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:warningSetting:search")
    public ResultResp<EarlyWarningResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        EarlyWarningResp warningSettingResp = ConvertUtils.copy(earlyWarningService.getById(req.getId()), EarlyWarningResp.class);
        List<EarlyWarningThresholdResp> thresholdResps = earlyWarningService.getEarlyWarningThreshold(req.getId())
                .stream().map(item -> ConvertUtils.copy(item, EarlyWarningThresholdResp.class))
                .collect(Collectors.toList());
        warningSettingResp.setWarningThresholds(thresholdResps);
        List<EarlyWarningUserResp> userResps = earlyWarningService.getEarlyWarningUser(req.getId())
                .stream().map(item -> ConvertUtils.copy(item, EarlyWarningUserResp.class))
                .collect(Collectors.toList());
        warningSettingResp.setWarningUsers(userResps);
        return ResultResp.success(warningSettingResp);
    }

    /**
     * 组装查询条件
     */
    private static JoinLambdaWrapper<EarlyWarningEntity> buildQW(EarlyWarningQueryReq req) {
        return Joins.of(EarlyWarningEntity.class)
                .leftJoin(SceneProjectEntity.class, SceneProjectEntity::getId, EarlyWarningEntity::getSceneProjectId)
                .select(SceneProjectEntity::getProjectName)
                .end()
                .leftJoin(MeterDeviceEntity.class, MeterDeviceEntity::getId, EarlyWarningEntity::getMeterDeviceId)
                .select(MeterDeviceEntity::getDeviceName)
                .eq(StringUtils.isNotEmpty(req.getEnergyTypeId()), MeterDeviceEntity::getEnergyTypeId, req.getEnergyTypeId())
                .end()
                .leftJoin(EnergyConsumptionTypeEntity.class, EnergyConsumptionTypeEntity::getId, MeterDeviceEntity::getEnergyTypeId)
                .selectAs(EnergyConsumptionTypeEntity::getEnergyName, EarlyWarningResp::getEnergyTypeName)
                .end()
                .eq(EarlyWarningEntity::getWarningType, IEarlyWarningEnums.WarningType.warningType2.warningType)
                .in(CollectionUtils.isNotEmpty(req.getWarningTypeList()), EarlyWarningEntity::getWarningType, req.getWarningTypeList())
                .like(StringUtils.isNotEmpty(req.getWarningName()), EarlyWarningEntity::getWarningName, req.getWarningName())
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), EarlyWarningEntity::getSceneProjectId, req.getSceneProjectId())
                .eq(StringUtils.isNotEmpty(req.getSceneEdificeId()), EarlyWarningEntity::getSceneEdificeId, req.getSceneEdificeId())
                .eq(StringUtils.isNotEmpty(req.getSceneFloorId()), EarlyWarningEntity::getSceneFloorId, req.getSceneFloorId())
                .eq(StringUtils.isNotEmpty(req.getSceneRoomId()), EarlyWarningEntity::getSceneRoomId, req.getSceneRoomId())
                .eq(StringUtils.isNotEmpty(req.getMeterDeviceId()), EarlyWarningEntity::getMeterDeviceId, req.getMeterDeviceId())
                .eq(StringUtils.isNotEmpty(req.getMeterCondition()), EarlyWarningEntity::getMeterCondition, req.getMeterCondition())
                .in(CollectionUtils.isNotEmpty(req.getMeterConditionList()), EarlyWarningEntity::getMeterCondition, req.getMeterConditionList())
                .eq(StringUtils.isNotEmpty(req.getPushType()), EarlyWarningEntity::getPushType, req.getPushType())
                .in(CollectionUtils.isNotEmpty(req.getPushTypeList()), EarlyWarningEntity::getPushType, req.getPushTypeList())
                .eq(req.getStartTime() != null, EarlyWarningEntity::getStartTime, req.getStartTime())
                .eq(req.getEndTime() != null, EarlyWarningEntity::getEndTime, req.getEndTime())
                .eq(StringUtils.isNotEmpty(req.getDeptId()), EarlyWarningEntity::getDeptId, req.getDeptId())
                .in(CollectionUtils.isNotEmpty(req.getIds()), EarlyWarningEntity::getId, req.getIds())
                .last(StringUtils.isNotEmpty(req.getSortColumn()), PageUtils.lastOrderBy(req))
                .orderByDesc(StringUtils.isEmpty(req.getSortColumn()), EarlyWarningEntity::getCreateTm);
    }

    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:warningSetting:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) EarlyWarningReq req) {
        req.setWarningType(IEarlyWarningEnums.WarningType.warningType2.warningType);
        boolean res = earlyWarningService.saveEarlyWarning(ConvertUtils.convertIgnoreId(req, EarlyWarningEntity.class), req.getUserIds(), req.getThresholdJson());
        return ResultResp.success(res);
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:warningSetting:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) EarlyWarningReq req) {
        req.setWarningType(IEarlyWarningEnums.WarningType.warningType2.warningType);
        boolean res = earlyWarningService.updateEarlyWarning(ConvertUtils.copy(req, EarlyWarningEntity.class), req.getUserIds(), req.getThresholdJson());
        return ResultResp.success(res);
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:warningSetting:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(earlyWarningService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:warningSetting:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(earlyWarningService.removeBatchByIds(req.getIds(), 1000));
    }

    @ApiOperation("导入")
    @PostMapping("upload")
    @RequiresPermissions("ecp-admin:warningSetting:upload")
    public ResultResp<Integer> upload(@RequestParam("file") MultipartFile file, Boolean ignoreError) {
        return ResultResp.success(ExcelParseManage.i().process(EarlyWarningRenderer.ENTITY_NAME, file, ignoreError));
    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:warningSetting:export")
    public void export(@RequestBody @Validated(IExport.class) EarlyWarningQueryReq req, HttpServletResponse response) {
        ExcelXSSFUtil.export("EarlyWarningExport", JsonUtil.toJson(earlyWarningService.list(buildQW(req)), new IEarlyWarningFilter.EarlyWarningExportFilter()), response);
    }
}
